document.addEventListener('DOMContentLoaded', function() {
    // 状态切换显示和隐藏字段更新
    const statusCheckbox = document.getElementById('status');
    const statusLabel = document.querySelector('.status-label');
    const statusHiddenInput = document.querySelector('input[name="_status"]');

    if (statusCheckbox && statusLabel && statusHiddenInput) {
        // 初始化状态
        statusHiddenInput.value = statusCheckbox.checked ? 'on' : 'off';

        statusCheckbox.addEventListener('change', function() {
            statusLabel.textContent = this.checked ? '启用' : '禁用';
            statusHiddenInput.value = this.checked ? 'on' : 'off';
        });
    }

    // 表单验证
    const form = document.querySelector('.edit-form');
    if (form) {
        form.addEventListener('submit', function(event) {
            let isValid = true;

            // 验证职位名称
            const nameInput = document.getElementById('positionName');
            if (!nameInput.value.trim()) {
                isValid = false;
                showError(nameInput, '职位名称不能为空');
            } else if (nameInput.value.trim().length > 50) {
                isValid = false;
                showError(nameInput, '职位名称不能超过50个字符');
            } else {
                clearError(nameInput);
            }

            // 验证职位代码
            const codeInput = document.getElementById('positionCode');
            if (!codeInput.value.trim()) {
                isValid = false;
                showError(codeInput, '职位代码不能为空');
            } else if (codeInput.value.trim().length > 20) {
                isValid = false;
                showError(codeInput, '职位代码不能超过20个字符');
            } else {
                clearError(codeInput);
            }

            if (!isValid) {
                event.preventDefault();
            }
        });
    }

    function showError(input, message) {
        const formGroup = input.closest('.form-group');
        let errorElement = formGroup.querySelector('.error-message');

        if (!errorElement) {
            errorElement = document.createElement('div');
            errorElement.className = 'error-message';
            formGroup.appendChild(errorElement);
        }

        errorElement.textContent = message;
        input.classList.add('has-error');
    }

    function clearError(input) {
        const formGroup = input.closest('.form-group');
        const errorElement = formGroup.querySelector('.error-message');

        if (errorElement) {
            errorElement.remove();
        }

        input.classList.remove('has-error');
    }
});